package com.lagou.java.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.Security;
import java.util.Base64;

public class EncryptUtil {

    static {
        // 把BouncyCastle作为Provider添加到java.security:
        Security.addProvider(new BouncyCastleProvider());
    }

    public static void main(String[] args) throws Exception {

        String saltStr = "password";
        // 原文:
        String message = "Hello, world!";
        // 加密口令:~z`
        String password = "hello12345";
        // 加密:
        String secrete = encrypt(password, saltStr, message);
        System.out.println("encrypted: " + secrete);
        // 解密:
        String oringeMsg = decrypt(password, saltStr, secrete);

        System.out.println("decrypted: " + oringeMsg);
    }

    // 加密:
    public static String encrypt(String password, String saltStr, String message) throws Exception {
        byte[] salt = saltStr.getBytes();
        byte[] input = message.getBytes("UTF-8");
        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory skeyFactory = SecretKeyFactory.getInstance("PBEwithSHA1and128bitAES-CBC-BC");
        SecretKey skey = skeyFactory.generateSecret(keySpec);
        PBEParameterSpec pbeps = new PBEParameterSpec(salt, 1000);
        Cipher cipher = Cipher.getInstance("PBEwithSHA1and128bitAES-CBC-BC");
        cipher.init(Cipher.ENCRYPT_MODE, skey, pbeps);
        byte[] bytes = cipher.doFinal(input);
        return Base64.getEncoder().encodeToString(bytes);
    }

    // 解密:
    public static String decrypt(String password, String saltStr, String encryptedData) throws Exception {
        byte[] salt = saltStr.getBytes();
        byte[] input = Base64.getDecoder().decode(encryptedData);
        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory skeyFactory = SecretKeyFactory.getInstance("PBEwithSHA1and128bitAES-CBC-BC");
        SecretKey skey = skeyFactory.generateSecret(keySpec);
        PBEParameterSpec pbeps = new PBEParameterSpec(salt, 1000);
        Cipher cipher = Cipher.getInstance("PBEwithSHA1and128bitAES-CBC-BC");
        cipher.init(Cipher.DECRYPT_MODE, skey, pbeps);
        byte[] bytes = cipher.doFinal(input);
        return new String(bytes, "UTF-8");
    }
}